package nuist.hanniko.stu.webbackend.dao.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RealTimeRecordDAO {

    private final RedisTemplate<String, String> redisTemplate;

    private static final String AUTO_UP = "AUTO_UP";
    private static final String AUTO_UP_ERR = "AUTO_UP_ERR";

    @Autowired
    public RealTimeRecordDAO(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public JSONArray getDevice(String deviceId) {
        return (JSONArray) JSON.parse((String) redisTemplate.opsForHash().get(AUTO_UP, deviceId));
    }

    public JSONArray getObject(String deviceId, String objectId) {
        JSONArray resultArray = new JSONArray();

        JSONArray tmp = (JSONArray) JSON.parse((String) redisTemplate.opsForHash().get(AUTO_UP, deviceId));

        for (JSONObject object :
                tmp.toJavaList(JSONObject.class)) {
            if (objectId.equals(object.get("object_id"))) {
                tmp.add(object);
            }
        }

        return resultArray;
    }

    public JSONArray getResource(String deviceId, String objectId, String resourceId) {
        JSONArray resultArray = new JSONArray();

        JSONArray tmp = (JSONArray) JSON.parse((String) redisTemplate.opsForHash().get(AUTO_UP, deviceId));

        for (JSONObject object :
                tmp.toJavaList(JSONObject.class)) {
            if (objectId.equals(object.get("object_id")) && resourceId.equals(object.get("resource_id"))) {
                tmp.add(object);
            }
        }

        return resultArray;
    }

    public JSONArray getAllData() {
        JSONArray resultArray = new JSONArray();
        Map<Object, Object> data = redisTemplate.boundHashOps(AUTO_UP).entries();

        for (Map.Entry entry : data.entrySet()) {
            resultArray.add(JSON.parseArray(entry.getValue().toString()));
        }

        return resultArray;
    }
}